<template>
  <div class="data-container">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card class="data-card">
          <template #header>
            <div class="card-header">
              <el-icon><Money /></el-icon>
              <span>今日门票收入</span>
            </div>
          </template>
          <div class="card-value">¥{{ todayIncome }}</div>
          <div class="card-compare">
            较昨日 <span :class="incomeChange >= 0 ? 'up' : 'down'">{{ incomeChange }}%</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="data-card">
          <template #header>
            <div class="card-header">
              <el-icon><User /></el-icon>
              <span>系统用户数</span>
            </div>
          </template>
          <div class="card-value">{{ userCount }}</div>
          <div class="card-compare">
            本月新增 <span class="up">{{ newUsers }}</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="data-card">
          <template #header>
            <div class="card-header">
              <el-icon><ChatRound /></el-icon>
              <span>今日动态数</span>
            </div>
          </template>
          <div class="card-value">{{ todayPosts }}</div>
          <div class="card-compare">
            较昨日 <span :class="postsChange >= 0 ? 'up' : 'down'">{{ postsChange }}%</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="data-card">
          <template #header>
            <div class="card-header">
              <el-icon><Ticket /></el-icon>
              <span>今日核销票数</span>
            </div>
          </template>
          <div class="card-value">{{ todayChecked }}</div>
          <div class="card-compare">
            <span v-if="todayChecked == 0" :class="todayChecked == 0 ? 'down' : 'up'">{{ todayChecked == 0 ? '今日无游客访问' : todayChecked }}</span>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <div class="chart-container">
      <el-card>
        <div id="incomeChart" style="height: 400px"></div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'
import { Money, User, ChatRound, Ticket } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { dataAPI } from '@/utils/api'

// 数据统计
const todayIncome = ref(0)
const incomeChange = ref(0)
const userCount = ref(0)
const newUsers = ref(0)
const todayPosts = ref(0)
const postsChange = ref(0)
const todayChecked = ref(0)

// 获取首页统计数据
const getHomeStats = () => {
  dataAPI.getHomeData().then(res => {
    if(res.data.code === 200){
      const data = res.data.data
      
      // 处理今日收入数据
      todayIncome.value = data.todayAmount || 0
      
      // 计算收入变化百分比
      if(data.yestdayAmount === 0 || data.yestdayAmount === undefined){
        incomeChange.value = data.todayAmount > 0 ? 100 : 0;
      }else{
        incomeChange.value = ((data.todayAmount - data.yestdayAmount) / data.yestdayAmount * 100).toFixed(1)
      }
      
      // 用户数据
      userCount.value = data.totalUser || 0
      newUsers.value = data.toMonthTotalUser || 0
      
      // 博客数据
      todayPosts.value = data.toDayBlogTotal || 0
      
      // 计算博客变化百分比
      if (data.yestdayBlogTotal === 0 || data.yestdayBlogTotal === undefined) {
        postsChange.value = data.toDayBlogTotal > 0 ? 100 : 0;
      } else {
        postsChange.value = ((data.toDayBlogTotal - data.yestdayBlogTotal) / data.yestdayBlogTotal * 100).toFixed(1)
      }
      
      // 票务数据
      todayChecked.value = data.usedCount || 0
      
      console.log('统计数据加载成功:', data)
    }else{
      console.error('统计数据接口错误:', res.data.message)
      ElMessage.error(res.data.message || '加载统计数据失败')
    }
  }).catch((err) => {
    console.error('统计数据加载失败:', err)
    ElMessage.error('统计数据加载失败')
  })
}

let refreshInterval;
let myChart = null;

// 清除图表相关资源
const disposeChart = () => {
  if (myChart) {
    myChart.dispose();
    myChart = null;
  }
}

// 初始化图表
onMounted(() => {
  // 获取统计数据
  getHomeStats();
  getOrderIncomeData();

  // 设置定时器，每2分钟刷新一次数据
  refreshInterval = setInterval(() => {
    getHomeStats();
    getOrderIncomeData();
  }, 120000);
});

onBeforeUnmount(() => {
  // 清除定时器
  if (refreshInterval) {
    clearInterval(refreshInterval);
    refreshInterval = null;
  }
  
  // 清除window的resize事件监听
  window.removeEventListener('resize', () => {
    if (myChart) myChart.resize();
  });
  
  // 清除图表
  disposeChart();
});

// 获取订单收入数据
const getOrderIncomeData = () => {
  dataAPI.getOrderStats().then(res => {
    if(res.data.code === 200){
      const data = res.data.data;
      const chartDom = document.getElementById('incomeChart');
      
      // 先清除旧图表
      disposeChart();
      
      // 创建新图表
      myChart = echarts.init(chartDom);
      
      const option = {
        title: {
          text: '近7天总门票收入统计',
          left: 'center',
          textStyle: {
            color: '#303133',
            fontWeight: 'bold',
            fontSize: 16
          }
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{b}<br/>{a}: ¥{c}'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '10%',
          top: '12%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: data.keys || [],
          axisLine: {
            lineStyle: {
              color: '#909399'
            }
          },
          axisLabel: {
            color: '#606266',
            fontSize: 12,
            formatter: function(value) {
              // 优化日期显示格式
              return value;
            },
            margin: 14,
            rotate: 0,
            interval: 0  // 显示所有标签
          },
          axisTick: {
            alignWithLabel: true
          },
          nameTextStyle: {
            color: '#909399',
            fontSize: 12,
            padding: [0, 0, 5, 0]
          },
          name: '日期'  // 添加横轴名称
        },
        yAxis: {
          type: 'value',
          name: '收入(元)',
          nameTextStyle: {
            color: '#909399',
            fontSize: 12,
            padding: [0, 30, 0, 0]
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#909399'
            }
          },
          axisLabel: {
            color: '#606266',
            fontSize: 12,
            formatter: '¥{value}'
          },
          splitLine: {
            lineStyle: {
              color: '#EBEEF5'
            }
          }
        },
        series: [
          {
            name: '门票收入',
            type: 'line',
            smooth: true,
            data: data.values || [],
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: 'rgba(24, 144, 255, 0.6)'
                  },
                  {
                    offset: 1,
                    color: 'rgba(24, 144, 255, 0.1)'
                  }
                ]
              }
            },
            itemStyle: {
              color: '#1890ff'
            },
            lineStyle: {
              width: 3
            },
            symbolSize: 7
          }
        ]
      };
      
      myChart.setOption(option);
      
      // 添加窗口大小改变时的事件监听
      window.addEventListener('resize', () => {
        if (myChart) myChart.resize();
      });
      
    }else{
      console.error('图表数据接口错误:', res.data.message);
      ElMessage.error(res.data.message || '加载图表数据失败');
    }
  }).catch((err) => {
    console.error('图表数据加载失败:', err);
    ElMessage.error('图表数据加载失败');
  });
};
</script>

<style scoped>
.data-container {
  padding: 20px;
}

.data-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  color: #606266;
}

.card-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin: 10px 0;
}

.card-compare {
  font-size: 14px;
  color: #909399;
}

.up {
  color: #67C23A;
}

.down {
  color: #F56C6C;
}

.chart-container {
  margin-top: 20px;
}
</style>